<?php
/**
 * Created by PhpStorm.
 * User: wzy12
 * Date: 2018/10/17
 * Time: 15:18
 */

namespace app\admin\model;


use think\Model;
use app\admin\validate\Order as Vali;

class Order extends Model
{
    public function goods(){
        return $this->hasMany('OrderGoods', 'order_id', 'id');
    }

    public function action(){
        return $this->hasMany('OrderAction', 'order_id', 'id');
    }

    public function deliver(){
        return $this->hasMany('Delivery', 'order_id', 'id');
    }

    public function resList($where){
        $query = $this -> where(1);

        // 筛选条件
        $is_where = $where;
        unset($is_where['page']);
        if($is_where) {
            if ($where) {
                // 查询时间日期
                if ($where['start'] && $where['end']) {
                    $add_time = search($where, 'add_time');
                    if ($add_time != 1) {
                        $query->where($add_time);
                    }
                }
                // 查询支付状态
                if ($where['pay_status'] || $where['pay_status'] === '0') {
                    $query->where('pay_status', $where['pay_status']);
                }
                // 查询发货状态
                if ($where['shipping_status'] || $where['shipping_status'] === '0') {
                    $query->where('shipping_status', $where['shipping_status']);
                }
                // 查询支付方式
                if ($where['pay_code']) {
                    $query->where('pay_code', $where['pay_code']);
                }
                // 查询订单状态
                if ($where['order_status'] || $where['order_status'] === '0') {
                    $query->where('order_status', $where['order_status']);
                }
                // 查询订单号
                if ($where['order_sn']) {
                    $query->where('order_sn', 'like', "%{$where['order_sn']}%");
                }
            }
        }

        $list['list'] = $query -> paginate(10, false, ['query'=>request()->param()]);

        // 支付方式
        $list['pay'] = model('Plugin') -> where('type', 'payment') -> where('status', 1) -> select();

        return $list;
    }

    // 修改订单
    public function operation($data){
        $temp = [];
        $goods_price = 0;
        foreach($data['goods'] as $k => $v){
            $temp[] = ['id' => $k, 'goods_num' => $v['goods_num']];
            $goods_price += $v['goods_num'] * $v['member_goods_price'];
        }

        // 支付方式
        if($data['pay']){
            $pay = explode('-', $data['pay']);
            $data['pay_code'] = $pay[0];
            $data['pay_name'] = $pay[1];
        }

        // 物流
        $shipping = explode('-', $data['shipping_code']);
        $data['shipping_code'] = $shipping[0];
        $data['shipping_name'] = $shipping[1];

        // 价格
        $data['goods_price'] = $goods_price;
        $data['total_amount'] = $goods_price + $data['shipping_price'];
        $data['order_amount'] = $goods_price + $data['shipping_price'] + $data['discount'];

        model('OrderGoods') -> isUpdate(true) -> saveAll($temp);

        // 验证
        $validate = new Vali();
        if(!$validate -> check($data)){
            return echoArr(0, $validate->getError());
        }
        $result = $this -> allowField(true) -> isUpdate(true) -> save($data);
        if(false === $result){
            return echoArr(0, $this -> getError());
        }else{
            return echoArr(1, '操作成功');
        }
    }

    // 修改费用
    public function editCost($data){
        $data['order_amount'] = $data['goods_price'] + $data['shipping_price'] + $data['discount'];
        $data['total_amount'] = $data['goods_price'] + $data['shipping_price'];

        // 验证
        $validate = new Vali();
        if(!$validate -> scene('cost') -> check($data)){
            return echoArr(0, $validate->getError());
        }

        $result = $this -> allowField(true) -> isUpdate(true) -> save($data);
        if(false === $result){
            return echoArr(0, $this -> getError());
        }else{
            return echoArr(1, '操作成功');
        }
    }

    // 查看订单
    public function Cat($id){
        // 订单商品详情
        $order = $this -> alias('o') -> join('Users u', 'o.user_id = u.id') -> field('o.*,u.username,u.email,u.mobile u_mobile') -> find($id);
        $order['goods'] = $order -> goods() -> alias('og') -> join('Goods g', 'og.goods_id = g.id') -> field('og.*,g.original_img') -> select();

        // 订单操作记录
        $order['action'] = $order -> action() -> order('id desc') -> select();
        $users = model('AdminUser') -> select();
        $temp = $order['action'];
        foreach($temp as $k => $v){
            foreach($users as $key => $val){
                if($v['action_user'] != 0){
                    if($v['action_user'] == $val['id']){
                        $temp[$k]['username'] = $val['username'];
                    }
                }
            }
        }

        // 支付列表
        $where = [
            'status' => 1,
            'type' => 'payment'
        ];
        $order['payment'] = model('Plugin') -> where($where) -> select();

        // 发票列表
        $order['invoice'] = model('Invoice') -> where('order_sn', $order['order_sn']) -> find();

        // 订单发货操作记录
        $order['deliver'] = $order -> deliver() -> alias('d') -> join('AdminUser u', 'd.admin_id = u.id') -> order('id desc') -> field('d.*,u.username') -> select();

        // 物流列表
        $order['shipping'] = model('Shipping') -> where('is_open', 1) -> field('shipping_name,shipping_code') -> select();

        return $order;
    }

    // 删除订单
    public function del($data){
        // 验证
        $validate = new Vali();
        if(!$validate -> scene('del') -> check($data)){
            return echoArr(0, $validate->getError());
        }

        // 记录管理员操作信息
        $data['log_tim'] = time();
        $res_action = model('OrderAction') -> allowField(true) -> isUpdate(false) -> save($data);

        // 删除订单内的所有商品
        $res_goods = model('OrderGoods') -> where('order_id', $data['order_id']) -> delete();

        if($res_goods !== false){
            $res = $this -> destroy($data['order_id']);

            if($res !== false){
                return echoArr(1, '操作成功');
            }else{
                return echoArr(0, '操作失败');
            }
        }else{
            return echoArr(0, '操作失败');
        }
    }

    /**
     * 资金统计
     */
    public function order_complete($where){
        $query = $this -> where(1);

        // 筛选条件
        $is_where = $where;
        unset($is_where['page']);
        if($is_where) {
            if ($where) {
                // 查询时间日期
                if ($where['start'] && $where['end']) {
                    $add_time = search($where, 'o.confirm_time');

                    if ($add_time != 1) {
                        $query->where($add_time);
                    }
                }
                // 查询支付方式
                if ($where['pay_code']) {
                    $query->where('o.pay_code', $where['pay_code']);
                }
                // 查询订单号
                if ($where['order_sn']) {
                    $query->where('o.order_sn', 'like', "%{$where['order_sn']}%");
                }
            }
        }

        $list = $query -> where('order_status', 4)
            -> alias('o')
            -> join('Users u', 'o.user_id = u.id')
            -> join('PayRecord p', 'p.order_sn = o.order_sn')
            -> field('o.*,u.username,u.mobile,p.pay_price')
            -> paginate(10, false, ['query'=>request()->param()]);

        // 所有订单金额和当天订单金额
        $count_money = 0;
        $day_money = 0;
        $today = strtotime(date("Y-m-d"),time());
        foreach($list as $k => $v){
            $count_money += $v['pay_price'];

            if($v['pay_time'] > $today){
                $day_money += $v['pay_price'];
            }
        }

        $result['list'] = $list;
        $result['count_money'] = $count_money;
        $result['day_money'] = $day_money;

        return $result;
    }

    /**
     * 发票管理
     */
    public function invoice($where){
        $query = $this -> where(1);

        // 筛选条件
        $is_where = $where;
        unset($is_where['page']);
        if($is_where) {
            if ($where) {
                // 查询时间日期
                if ($where['start'] && $where['end']) {
                    $add_time = search($where, 'confirm_time');

                    if ($add_time != 1) {
                        $query->where($add_time);
                    }
                }
                // 查询发票类型
                if ($where['invoice_type']) {
                    $query->where('invoice_type', $where['invoice_type']);
                }
                // 查询订单号
                if ($where['order_sn']) {
                    $query->where('order_sn', 'like', "%{$where['order_sn']}%");
                }
            }
        }

        $list = $query -> where('order_status', 4) -> paginate(10);

        return $list;
    }

    /**
     * 发货单
     */
    public function deliver_goods($where){
        $query = $this -> where(1);

        // 筛选条件
        $is_where = $where;
        unset($is_where['page']);
        if($is_where) {
            if ($where) {
                // 查询发货状态
                if ($where['shipping_status'] || $where['shipping_status'] === '0') {
                    $query->where('shipping_status', $where['shipping_status']);
                }
                // 查询订单号
                if ($where['order_sn']) {
                    $query->where('order_sn', 'like', "%{$where['order_sn']}%");
                }
                // 查询订单号
                if ($where['consignee']) {
                    $query->where('consignee', 'like', "%{$where['consignee']}%");
                }
            }
        }

        $list = $query -> where('shipping_status', 'in', [0, 2]) -> where('order_status', 1) -> paginate(10);

        return $list;
    }
}